<template>
  <div class="color-editor flex items-center gap-3">
    <input
      type="color"
      v-model="currentValue"
      class="w-10 h-10 p-0 border border-gray-300 rounded cursor-pointer"
      @input="$emit('input', currentValue)"
    >
    <div class="flex-1">
      <input
        type="text"
        v-model="currentValue"
        class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary text-sm"
        placeholder="#RRGGBB 或 rgb()"
        @input="handleTextInput"
      >
    </div>
    <div 
      class="w-8 h-8 rounded border border-gray-300"
      :style="{ backgroundColor: currentValue }"
    ></div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';

export default {
  props: {
    value: {
      type: String,
      default: '#000000'
    }
  },
  emits: ['input'],
  setup(props) {
    const currentValue = ref(props.value);
    const isValidColor = computed(() => {
      // 简单验证颜色格式
      const colorRegex = /^(#([0-9A-Fa-f]{3}){1,2}|rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)|rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[0-1](\.\d+)?\s*\))$/;
      return colorRegex.test(currentValue.value);
    });

    // 监听外部值变化
    watch(
      () => props.value,
      (newVal) => {
        currentValue.value = newVal;
      }
    );

    // 处理文本输入
    const handleTextInput = (e) => {
      const value = e.target.value;
      currentValue.value = value;
      // 触发输入事件，即使格式无效也允许，方便用户修正
      $emit('input', value);
    };

    return {
      currentValue,
      isValidColor,
      handleTextInput
    };
  }
};
</script>

<style scoped>
input[type="text"]:not(.is-valid) {
  border-color: #e53e3e !important;
}
</style>
    